package main

// @title Data-API-MCP API
// @version 1.0
// @description 数据库连接管理和操作API服务
// @termsOfService http://swagger.io/terms/

// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

// @host localhost:8080
// @BasePath /api/v1
// @schemes http https

// @securityDefinitions.apikey Bearer
// @in header
// @name Authorization
// @description Type "Bearer" followed by a space and JWT token.

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"Data-API-MCP/backend/configs"
	"Data-API-MCP/backend/internal/application/usecase"
	"Data-API-MCP/backend/internal/base/logger"
	"Data-API-MCP/backend/internal/domain/service"
	"Data-API-MCP/backend/internal/infrastructure/persistence"
	"Data-API-MCP/backend/internal/interfaces/http/handler"
	"Data-API-MCP/backend/internal/interfaces/http/router"

	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	"go.uber.org/zap"
)

func main() {
	// 加载配置
	config, err := configs.LoadConfig()
	if err != nil {
		log.Fatalf("加载配置失败: %v", err)
	}

	// 初始化日志
	if err := logger.InitLogger(config); err != nil {
		log.Fatalf("初始化日志失败: %v", err)
	}
	defer logger.Log.Sync()

	// 初始化数据库
	if err := persistence.InitDB(config); err != nil {
		logger.Fatal("初始化数据库失败", zap.Error(err))
	}
	defer persistence.CloseDB()

	// 初始化用户用例
	userService := service.NewUserService(persistence.NewUserRepository(persistence.GetDB()), config)
	// 初始化用户用例
	userUseCase := usecase.NewUserUseCase(userService)
	// 初始化用户服务
	userHandler := handler.NewUserHandler(userUseCase)

	// 初始化数据库连接池
	dbPool := persistence.NewDBPool(persistence.GetDB())
	// 初始化审计日志仓库
	auditRepo := persistence.NewAuditRepository(persistence.GetDB())
	// 初始化数据库服务
	dbService := service.NewDBService(persistence.NewDBRepository(persistence.GetDB()))
	// 初始化处理器
	dbHandler := handler.NewDBHandler(dbService, dbPool, auditRepo, logger.Log)

	// 初始化API管理服务
	apiService := service.NewAPIService(persistence.NewAPIRepository(persistence.GetDB()), dbService)
	// 初始化API管理处理器
	apiHandler := handler.NewAPIHandler(apiService)

	// 初始化统计仓库
	statsRepo := persistence.NewStatisticsRepository(persistence.GetDB())
	// 初始化统计服务
	statsService := service.NewStatisticsService(statsRepo)
	// 初始化统计处理器
	statsHandler := handler.NewStatisticsHandler(statsService)

	// 初始化MCP仓库
	mcpRepo := persistence.NewMCPRepository(persistence.GetDB())
	// 初始化MCP服务
	mcpService := service.NewMCPService(mcpRepo)
	// 初始化MCP处理器
	mcpHandler := handler.NewMCPServiceHandler(mcpService, logger.Log)

	handlers := router.Handlers{
		UserHandler:       userHandler,
		DBHandler:         dbHandler,
		APIHandler:        apiHandler,
		StatisticsHandler: statsHandler,
		MCPHandler:        mcpHandler,
	}

	// 设置路由
	r := router.SetupRouter(config, &handlers)

	// 注册Swagger文档路由
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	// 创建HTTP服务器
	srv := &http.Server{
		Addr:    fmt.Sprintf("%s:%d", config.Server.Host, config.Server.Port),
		Handler: r,
	}

	// 启动服务器
	go func() {
		logger.Info("正在启动服务器...", zap.String("addr", srv.Addr))
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Fatal("启动服务器失败", zap.Error(err))
		}
	}()

	// 等待中断信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	// 优雅关闭
	logger.Info("正在关闭服务器...")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		logger.Fatal("服务器被迫关闭", zap.Error(err))
	}

	logger.Info("服务器退出")
}
